package system.base;

import com.hitrust.gs.dao.GSManufactureDAO;
import com.hitrust.gs.lib.GSBaseConstants;

import system.LoginContext;
import system.data.ProductPageData;
import system.data.WarehouseCategoryPageData;
import framework.core.BizException;
import framework.core.Conditions;
import framework.core.ConstDefine;
import framework.core.DBConnection;
import framework.core.DateUtil;
import framework.core.IHandler;
import framework.core.ILoginContext;
import framework.core.Logger;
import framework.core.ObjectList;
import framework.core.PageData;
import framework.core.SearchEvent;
import framework.core.SrvContext;

/*
 Author    :chengbiao.he
 CreateTime:2008-01-30 14:21:49
 */
public class ProductSrv extends IHandler {

    public ProductSrv() {
        super();
    }

    private void deleteProduct(DBConnection con, SrvContext context) throws Exception {
        String[] ids = context.getParameterValues("ids");
        Product obj = null;
        for (int i = 0; i < ids.length; i++) {
            obj = Product.fetch(con, ids[i]);
            if (obj != null)
                obj.delete(con);
        }
    }
    
    private boolean checkProductWasAlreadySaved(String concentricityCode,String id,DBConnection con){
        Product pro = null; 
        try {
            pro = Product.fetchByConcentricityCode(con, concentricityCode);
        } catch (Exception e) {
            
            e.printStackTrace();
        }
        //没有查到产品    数据库不存在相同编码
        if(pro == null){
            return true;
        }
        //此为新添加 基于上一条件  
        if(id == null || id.equals("")){
            return false;
        }
        //此为同一产品更新  基于前两条件
        if(pro.getId().equals(id)){
            return true;
        }
        //其他条件均假
        return false;
    }
    
    private boolean saveProduct(DBConnection con, SrvContext context, ILoginContext loginContext) throws Exception {
        String id = context.getString("Id", null);
        String categorycode = context.getString("Category", "");
        String concentricityCode = context.getString("ConcentricityCode", "");
        Product obj;
        ProductPageData data = (ProductPageData) PageData.fromForm(context, ProductPageData.class);
        if ((id == null) || (id.equals(""))) // add
        {
            obj = Product.fetch();
            data.setCategoryCode(categorycode);
            data.setCreateUserId(loginContext.getLoginUserId());
            data.setCreateUser(loginContext.getLoginUserName());
            data.setCreateTime(new DateUtil().getFullString());
            data.setWarehouseCode(loginContext.getLoginWarehouseCode());
            data.setWarehouseName(loginContext.getLoginWarehouseName());
            data.setConcentricityCode(concentricityCode);
            data.setIsBuy(ConstDefine.STR_YES);
            if("".equals(data.getApepCode())){
                data.setApepCode(data.getConcentricityCode());
            }
            
            Product other = Product.fetchByConcentricityCode(con, data.getConcentricityCode());
            if(other != null){
                context.setValue("ProductPageData", data);
                context.setErrorMsg("产品编码已经存在，请退出后生成新的产品编码再录入。");
                return false;
            }
        } else // update
        {
            if(checkProductWasAlreadySaved(concentricityCode, id, con)){
                obj = Product.fetch(con, id);
                String apepcode = data.getApepCode();
                if(apepcode == null || apepcode.equals("")){
                    data.setApepCode(obj.getConcentricityCode());
                }
                data.setConcentricityCode(concentricityCode);
            }else{
                context.setValue("ProductPageData", data);
                context.setErrorMsg("产品编码已经存在，请退出后生成新的产品编码再录入。");
                return true;
            }
        }
        data.setLastUpdateUserId(loginContext.getLoginUserId());
        data.setLastUpdateUser(loginContext.getLoginUserName());
        data.setLastUpdateTime(new DateUtil().getFullString());
        context.setValue("ProductPageData", data);
        obj.fill(data);
        obj.save(con);
        
        String categoryCode = context.getString("CategoryCode1", "");
        WarehouseCategoryRelation relation = new WarehouseCategoryRelation();
        Conditions conditions = new Conditions();
        conditions.add(WarehouseCategory.CATEGORY_CODE, categoryCode);
        WarehouseCategory category = WarehouseCategory.fetch(con, conditions);
        if(category != null){
            relation.setWarehouseCode(loginContext.getLoginWarehouseCode());
            relation.setWarehouseName(loginContext.getLoginWarehouseName());
            relation.setCategoryCode(category.getCategoryCode());
            relation.setProductCode(obj.getConcentricityCode());
            
            double order = 1;
            WarehouseCategoryRelation wobj = WarehouseCategoryRelation.fetchGetDisplayOrder(con);
            if(wobj != null) order = wobj.getDisplayOrder() + 1;
            relation.setDisplayOrder(order);
            relation.setStatus("1");
            relation.setCreateUserId(loginContext.getLoginUserId());
            relation.setCreateUser(loginContext.getLoginUserName());
            relation.setCreateTime(new DateUtil().getFullString());
            relation.setLastUpdateUserId(loginContext.getLoginUserId());
            relation.setLastUpdateUser(loginContext.getLoginUserName());
            relation.setLastUpdateTime(new DateUtil().getFullString());
            relation.save(con);
        }
        //else{
        //    context.setErrorMsg("报表分类没有添加，请进入报表分类管理设置分类。");
        //}
        
        return true;
    }

    private void listProduct(DBConnection con, ILoginContext login, SrvContext context, String path) throws Exception {
    	ProductSearchTempEvent event = (ProductSearchTempEvent) SearchEvent.fromForm(context, ProductSearchTempEvent.class); 
        //event.setProviderStatus("1");
        //event.setStatus("1");
        //event.setIsBuy("1");        	
        //event.setWarehouseCode(login.getLoginWarehouseCode());
        /*
        if (!event.getProviderCode().equals("")) {
            Conditions cs = new Conditions();
            cs.add(Provider.NAME, event.getProviderCode());
            ObjectList list = Provider.fetch().search(con, cs);
            if (list.size() > 0) {
                String[] providerCodes = new String[list.size()];
                for (int i = 0; i < list.size(); i++) {
                    Provider pro = (Provider) list.get(i);
                    providerCodes[i] = pro.getCode();
                }
                event.setProviderCodes(providerCodes);
            }
        }
        */
        if(GSBaseConstants.PLANPRICE.equals("true")){
            context.setValue("isPlanprice", "1");
        }else{
            context.setValue("isPlanprice", "0");
        }
        context.setSessionValue("ProductSearchEvent", event);
        context.setNextUrl(path + "ProductList.jsp");
    }
    
    private void listTempProduct(DBConnection con, SrvContext context, String path) throws Exception
    {
        LoginContext loginInfo = LoginContext.get(context);
        String userId = loginInfo.getLoginUserId();
        GSManufactureDAO tGSManufactureDAO = new GSManufactureDAO();
        boolean canChange = tGSManufactureDAO.canChangeTemporary(userId);
        
               
           //context.setSessionValue("UserMenuinfoList", userMenuinfoList);

        ProductSearchEvent event = (ProductSearchEvent) SearchEvent.fromForm(context, ProductSearchEvent.class);
        event.setIsNormal(ConstDefine.STR_NO);
        context.setSessionValue("ProductSearchEvent", event);
        if(canChange){
            context.setValue("canAuditing", "2");
        }else{
            context.setValue("canAuditing", "2");
        }
        if(GSBaseConstants.PLANPRICE.equals("true")){
            context.setValue("isPlanprice", "1");
        }else{
            context.setValue("isPlanprice", "0");
        }
        
        if(GSBaseConstants.AUDITING.equals("true")){
            context.setValue("auditing", "3");
        }else{
            context.setValue("auditing", "3");
        }
        context.setNextUrl(path + "ProductTempList.jsp");
    }
    
    private void listTempProductAuditing(DBConnection con, SrvContext context, String path) throws Exception
    {
        LoginContext loginInfo = LoginContext.get(context);
        String userId = loginInfo.getLoginUserId();
        GSManufactureDAO tGSManufactureDAO = new GSManufactureDAO();
        boolean canChange = tGSManufactureDAO.canChangeTemporary(userId);
        
               
           //context.setSessionValue("UserMenuinfoList", userMenuinfoList);

        ProductSearchEvent event = (ProductSearchEvent) SearchEvent.fromForm(context, ProductSearchEvent.class);
        event.setIsNormal(ConstDefine.STR_NO);
        context.setSessionValue("ProductSearchEvent", event);
        if(canChange){
            context.setValue("canAuditing", "1");
        }else{
            context.setValue("canAuditing", "0");
        }
        if(GSBaseConstants.PLANPRICE.equals("true")){
            context.setValue("isPlanprice", "1");
        }else{
            context.setValue("isPlanprice", "0");
        }
        
        if(GSBaseConstants.AUDITING.equals("true")){
            context.setValue("auditing", "1");
        }else{
            context.setValue("auditing", "0");
        }
        context.setNextUrl(path + "ProductTempListAuditing.jsp");
    }

    private void listProductWarehouseCategoryRelation(DBConnection con, SrvContext context, String path) throws Exception {
        WarehouseCategoryRelationSearchEvent event = (WarehouseCategoryRelationSearchEvent) SearchEvent.fromForm(context,
                WarehouseCategoryRelationSearchEvent.class);
        ProductSearchEvent proEvent = new ProductSearchEvent();
        
        if (!event.getCategoryCode().equalsIgnoreCase("")) {
            Conditions cs = new Conditions();
            cs.add(Product.CONCENTRICITY_CODE + " in (select product_code from t_warehouse_category_relation where category_code=?)", Conditions.CUSTOM, event
                    .getCategoryCode());
            ObjectList list = Product.fetch().search(con, cs);
            if (list.size() > 0) {
                String[] productCodes = new String[list.size()];
                for (int i = 0; i < list.size(); i++) {
                    Product pro = (Product) list.get(i);
                    productCodes[i] = pro.getConcentricityCode();
                }
                proEvent.setProductCodes(productCodes);
            }
        }
        context.setSessionValue("ProductSearchEvent", proEvent);
        context.setNextUrl(path + "AddProductList.jsp");
    }

    private void deleteWarehouseCategoryRelation(DBConnection con, SrvContext context) throws Exception {
        String[] ids = context.getParameterValues("ids");
        WarehouseCategoryRelation wcr = null;
        for (int i = 0; i < ids.length; i++) {
            wcr = WarehouseCategoryRelation.fetch(con,ids[i]);
            if (wcr != null) {
                wcr.delete(con);
            } else {
                throw new BizException("该产品未在当前分类下，或已经被删除!!!!!");
            }     
        }
    }

    private void backProduct(DBConnection con, SrvContext context, String path) throws Exception {
        context.setNextUrl(path + "ProductList.jsp");
    }

    public void doAction(DBConnection con, SrvContext context, ILoginContext loginContext) throws Exception {

        String action_code = context.getActionCode();
        String path = "/system/base/";

        if (action_code.equalsIgnoreCase("listProduct")) {
            listProduct(con, loginContext, context, path);
            return;
        }

        if (action_code.equalsIgnoreCase("viewProduct")) {
            String id = context.getString("Id", null);
            String relationId = context.getString("RelationId", null);
            Product obj = new Product();
            if (id != null) {
                obj = Product.fetch(con, id);
            } else if (relationId != null) {
                WarehouseCategoryRelation wcr = WarehouseCategoryRelation.fetch(con, relationId);
                obj = Product.fetchByConcentricityCode(con, wcr.getProductCode());
            }
            context.setValue("Product", obj);
            context.setNextUrl(path + "ProductView.jsp");
            return;
        }
        // add by chengbiao.he start
        if (action_code.equalsIgnoreCase("viewProduct")) {
            String id = context.getString("Id", null);
            Product obj = Product.fetch(con, id);
            context.setValue("Product", obj);
            context.setNextUrl(path + "ProductView.jsp");
            return;
        }
        // add by chengbiao.he end

        if (action_code.equalsIgnoreCase("deleteProduct")) {
            context.setErrorUrl(path + "ProductList.jsp");
            deleteProduct(con, context);
            backProduct(con, context, path);
            return;
        }

        if (action_code.equalsIgnoreCase("toAddProduct")) {
            Product obj = Product.fetch();
            ProductPageData data = (ProductPageData) PageData.fromTable(obj, ProductPageData.class);
            data.setWarehouseCode(loginContext.getLoginWarehouseCode());
            data.setWarehouseName(loginContext.getLoginWarehouseName());
            context.setValue("ProductPageData", data);
            context.setNextUrl(path + "ProductEdit.jsp");
            return;
        }
        // add by chengbiao.he start
        if (action_code.equalsIgnoreCase("toAddWarehouseCategory")) {
            Product obj = Product.fetch();
            ProductPageData data = (ProductPageData) PageData.fromTable(obj, ProductPageData.class);
            // 设置只能加临时产品
            data.setIsNormal(ConstDefine.STR_NO);

            data.setWarehouseCode(loginContext.getLoginWarehouseCode());
            data.setWarehouseName(loginContext.getLoginWarehouseName());
            context.setValue("ProductPageData", data);
            context.setNextUrl(path + "ProductEdit.jsp");
            return;
        }

        if (action_code.equalsIgnoreCase("toProductManage")) {
            String id = context.getString("warehouseCategoryId", null);
            Conditions cs = new Conditions();
            cs.add("id", id.split(":")[0]);
            cs.add("WAREHOUSE_CODE", id.split(":")[1]);
            WarehouseCategory obj = WarehouseCategory.fetch(con, cs);
            WarehouseCategoryRelationSearchEvent wcrEvent = (WarehouseCategoryRelationSearchEvent) SearchEvent.fromForm(context, WarehouseCategoryRelationSearchEvent.class);
            wcrEvent.setCategoryCode(obj.getCategoryCode());
            wcrEvent.setWarehouseCode(obj.getWarehouseCode());
            context.setSessionValue("WarehouseCategoryRelationEvent", wcrEvent);
            //在此处放入分类ID (select * from T_WAREHOUSE_CATEGORY where ID='ID')
            context.setSessionValue("warehouseCategoryId", id.split(":")[0]);
            context.setNextUrl(path + "ProductManageList.jsp");
            return;
        }
        if (action_code.equalsIgnoreCase("toDeleteProductManage")) {
            String id = context.getString("Id", null);
            WarehouseCategory obj = WarehouseCategory.fetch(con, id);
            context.setValue("Product", obj);
            context.setNextUrl(path + "ProductManageList.jsp");
            return;
        }
        // add by chengbiao.he end
        if (action_code.equalsIgnoreCase("toUpdateProduct")) {

            context.setErrorUrl(path + "ProductList.jsp");
            String id = context.getString("Id", null);
            Product obj = Product.fetch(con, id);

            if (obj != null) {
                obj.canUpdateProduct(con, loginContext.getLoginWarehouseCode());
            }

            ProductPageData data = (ProductPageData) PageData.fromTable(obj, ProductPageData.class);
            context.setValue("ProductPageData", data);
            context.setNextUrl(path + "ProductEdit.jsp");

            return;
        }
        if (action_code.equalsIgnoreCase("toCopyProduct")) {
            String id = context.getString("Id", null);
            Product obj = Product.copy(Product.fetch(con, id));
            ProductPageData data = (ProductPageData) PageData.fromTable(obj, ProductPageData.class);
            context.setValue("ProductPageData", data);
            context.setNextUrl(path + "ProductEdit.jsp");
            return;
        }
        if (action_code.equalsIgnoreCase("saveProduct")) {
            boolean bz = false;
            context.setErrorUrl(path + "ProductEdit.jsp");
            bz = saveProduct(con, context, loginContext);
            if(bz == true){
                backProduct(con, context, path);
            }
            else{
                context.setNextUrl(path + "ProductEdit.jsp");
            }
            return;
        }
        if (action_code.equalsIgnoreCase("saveAndNewProduct")) {
            boolean bz = false;
            context.setErrorUrl(path + "ProductEdit.jsp");
            bz = saveProduct(con, context, loginContext);
            if(bz == true){
                Product obj = Product.fetch();
                ProductPageData data = (ProductPageData) PageData.fromTable(obj, ProductPageData.class);
                context.setValue("ProductPageData", data);
                context.setNextUrl(path + "ProductEdit.jsp");
            }
            else{
                context.setNextUrl(path + "ProductEdit.jsp");
            }
            return;
            //context.setErrorUrl(path + "ProductEdit.jsp");
            //saveProduct(con, context, loginContext);
//            Product obj = Product.fetch();
//
//            ProductPageData data = (ProductPageData) PageData.fromTable(obj, ProductPageData.class);
//            context.setValue("ProductPageData", data);
//            context.setNextUrl(path + "ProductEdit.jsp");
            //return;
        }
        if (action_code.equalsIgnoreCase("backListProduct")) {
            backProduct(con, context, path);
            return;
        }

        if (action_code.equalsIgnoreCase("addProduct")) {
            context.setErrorUrl(path + "ProductManageList.jsp");
            String categoryCode = context.getString("categoryCode", "");
            String warehouseCode = context.getString("warehouseCode", "");
            String searchWarehouseCode = context.getString("s_WarehouseCode", "");
            String isFirst = context.getString("isFirst", "");
            String isWarehouseCategoryProduct = context.getString("isWarehouseCategoryProduct", "");
            //context.setSessionValue("CategoryCodeV", categoryCode);
            //context.setSessionValue("WarehouseCodeV", warehouseCode);
            
            //add by Sindy start
            ProductSearchEvent event = (ProductSearchEvent) SearchEvent.fromForm(context, ProductSearchEvent.class);
            System.out.println(event.getCategoryCode()+"-------------------------");;
            //event.setCategoryCode("");
            event.setIsWarehouseCategoryProduct(isWarehouseCategoryProduct);
            event.setSearhWarehouseCode(searchWarehouseCode);
            /*
            if (!event.getCategoryCode().equalsIgnoreCase("")) {
                Conditions cs = new Conditions();
                cs.add(Product.CONCENTRICITY_CODE + " in (select product_code from t_warehouse_category_relation where category_code=?)", Conditions.CUSTOM, event
                        .getCategoryCode());
                ObjectList list = Product.fetch().search(con, cs);
                if (list.size() > 0) {
                    String[] productCodes = new String[list.size()];
                    for (int i = 0; i < list.size(); i++) {
                        Product pro = (Product) list.get(i);
                        productCodes[i] = pro.getConcentricityCode();
                    }
                    event.setProductCodes(productCodes);
                }
            }
            */
            context.setValue("isFirst", isFirst);
            context.setValue("categoryCode", categoryCode);
            context.setValue("warehouseCode", warehouseCode);
            context.setSessionValue("ProductSearchEvent", event);
            context.setNextUrl(path + "AddProductList.jsp");
            //add by Sindy end
            //listProductWarehouseCategoryRelation(con, context, path);
            context.setSessionValue("warehouseCategoryId",context.getString("warehouseCategoryId", ""));
            return;
        }
        if (action_code.equalsIgnoreCase("toAddWarehouseCategoryRelation")) {
            context.setErrorUrl(path + "AddProductList.jsp");
            ProductSearchEvent event = (ProductSearchEvent) SearchEvent.fromForm(context, ProductSearchEvent.class);
            String[] ids = context.getParameterValues("ids");
            String warehouseCode = (String) context.getString("warehouseCode");
            
            //add by Sindy start
            String warehouseName = "";
            if(!warehouseCode.equals(""))
                warehouseName = Warehouse.fetchByCode(con, warehouseCode).getName();
            else
                warehouseName = "";
            //add by Sindy end
            
            String categoryCode = (String) context.getString("categoryCode");
            Product obj = null;
            for (int i = 0; i < ids.length; i++) {
                obj = Product.fetch(con, ids[i]);
                String concentricityCode = obj.getConcentricityCode();
                Conditions condition = new Conditions();
                condition.add(WarehouseCategoryRelation.WAREHOUSE_CODE, warehouseCode);
                //condition.add(WarehouseCategoryRelation.CATEGORY_CODE, categoryCode);
                condition.add(WarehouseCategoryRelation.PRODUCT_CODE, concentricityCode);
                WarehouseCategoryRelation wcr = WarehouseCategoryRelation.fetch(con, condition);
                if (wcr != null) {
                    context.setValue("categoryCode", categoryCode);
                    context.setValue("warehouseCode", warehouseCode);
                    throw new BizException("该产品已属于某一分类，请重新选择产品！");
                } 
                else {
                    //add by Sindy start
                    double diso = 0;
                    if(WarehouseCategoryRelation.fetchGetDisplayOrder(con)==null){
                        diso = 0;
                    }else
                        diso = WarehouseCategoryRelation.fetchGetDisplayOrder(con).getDisplayOrder()+1;
                    //add by Sindy end
                    WarehouseCategoryRelation warehouseCategoryRelation = WarehouseCategoryRelation.fetch();
                    warehouseCategoryRelation.setCategoryCode(categoryCode);
                    warehouseCategoryRelation.setProductCode(obj.getConcentricityCode());
                    warehouseCategoryRelation.setDisplayOrder(diso);
                    warehouseCategoryRelation.setLastUpdateTime(new framework.core.DateUtil().getFullString());
                    warehouseCategoryRelation.setLastUpdateUser(loginContext.getLoginUserName());
                    warehouseCategoryRelation.setLastUpdateUserId(loginContext.getLoginUserId());
                    warehouseCategoryRelation.setWarehouseCode(warehouseCode);
                    warehouseCategoryRelation.setWarehouseName(warehouseName);
                    warehouseCategoryRelation.setStatus(ConstDefine.STR_VALID_YES);
                    warehouseCategoryRelation.setCreateUserId(loginContext.getLoginUserId());
                    warehouseCategoryRelation.setCreateUser(loginContext.getLoginUserName());
                    warehouseCategoryRelation.setCreateTime(new framework.core.DateUtil().getFullString());
                    warehouseCategoryRelation.save(con);
                }
            }
            
            WarehouseCategoryRelationSearchEvent wcrs = new WarehouseCategoryRelationSearchEvent();
            wcrs.setCategoryCode(categoryCode);
            wcrs.setWarehouseCode(warehouseCode);
            
            Conditions cs = new Conditions();
            cs.add(WarehouseCategory.CATEGORY_CODE,categoryCode);
            cs.add(WarehouseCategory.WAREHOUSE_CODE,warehouseCode);
            context.setSessionValue("WarehouseCategoryRelationEvent", wcrs);
            
            
            context.setSessionValue("warehouseCategoryId",context.getString("warehouseCategoryId", ""));
           
            
            
            context.setSessionValue("warehouseCategoryId", context.getString("warehouseCategoryId", ""));
            context.setNextUrl(path + "ProductManageList.jsp");
            return;
        }
        if (action_code.equalsIgnoreCase("toAddWarehouseRelation")) {
            listProductWarehouseCategoryRelation(con, context, path);
            return;
        }

        if (action_code.equalsIgnoreCase("deleteWarehouseCategoryRelation")) {
            context.setErrorUrl(path + "ProductManageList.jsp");
            deleteWarehouseCategoryRelation(con, context);
            context.setNextUrl(path + "ProductManageList.jsp");
            return;
        }
        
        if(action_code.equalsIgnoreCase("listTempProduct"))
        {
            listTempProduct(con, context, path);
            return;
        }
        if(action_code.equalsIgnoreCase("listTempProductAuditing"))
        {
            listTempProductAuditing(con, context, path);
            return;
        }
        // add by chengbiao.he end
        Logger.throwException("ProductSrv", "unknown action_code=" + action_code);

    }
}
